package com.source.thread.cc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

// volatile 不保证原子性
public class VDemo02 {

    // volatile 不保证原子性
    // 原子类的 Integer
    private volatile static AtomicInteger num = new AtomicInteger();

    public static void add(){
        // num++; // 不是一个原子性操作
       num.getAndIncrement(); // AtomicInteger + 1 方法， CAS

     //   num.getAndAdd(2);
    }

    public static void main(String[] args) {


          Runnable  r1= new Runnable() {
              @Override
              public void run() {
                  for (int i = 0; i < 10; i++) {
                      num.getAndIncrement();
                  }
              }
          };

        Runnable  r2= new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    num.getAndIncrement();
                }

            }
        };

        Runnable  r3= new Runnable() {
            @Override
            public void run() {
                num.getAndIncrement();
            }
        };


        Thread   th1 =new Thread(r1);
        Thread   th2 =new Thread(r1);
        Thread   th3 =new Thread(r1);


            th1.start();
            th2.start();
            th3.start();





      /*

        //理论上num结果应该为 2 万
        for (int i = 1; i <= 3; i++) {
            System.out.println(Thread.activeCount());
            new Thread(()->{
                for (int j = 0; j < 100 ; j++) {
              //     System.out.println(Thread.currentThread().getName() + " ###" + num);
                    try {
                        TimeUnit.MILLISECONDS.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    add();
                }
            }).start();
        }
        System.out.println(Thread.activeCount());
        while (Thread.activeCount()>2){ // main  gc
            Thread.yield();

        }
*/
      /*  while (Thread.activeCount()>2){ // main  gc
            Thread.yield();
        }*/
        System.out.println(Thread.currentThread().getName() + " -----------------------------------" + num);


    }
}
